<template>
  <div class="wrapLimit clx main">
    <div class="commodityDetail">
      <el-form ref="data" :model="data" :rules="rules1" class="form-baseinfo">
        <div class="basicInfo">
          <p class="title">物料基本信息</p>
          <div class="info">
            <el-form-item label="物料简称" prop="cName">
              <el-input v-model="data.cName" />
            </el-form-item>
            <el-form-item label="物料所属大类" prop="bigTypeId">
              <el-select v-model="data.bigTypeId" @change="bigTypeChange">
                <el-option v-for="item in bigType" :key="item.id" :label="item.cName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料大类编码">
              <el-input v-model="data.bigTypeName" readonly placeholder="由大类自动带出" />
            </el-form-item>
            <el-form-item label="物料所属中类" prop="centreTypeId">
              <el-select v-model="data.centreTypeId" @change="centreTypeChange">
                <el-option v-for="item in centreType" :key="item.id" :label="item.cName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料中类编码">
              <el-input v-model="data.centreTypeName" readonly placeholder="由中类自动带出" />
            </el-form-item>
            <el-form-item label="物料所属小类" prop="smallTypeId">
              <el-select v-model="data.smallTypeId" @change="smallTypeChange">
                <el-option v-for="item in smallType" :key="item.categoryNo" :label="item.cName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料小类编码">
              <el-input v-model="data.smallTypeName" readonly placeholder="由小类自动带出" />
            </el-form-item>
            <el-form-item label="上传物料图片" class="upload">
              <el-upload
                ref="upload"
                :action="public_config.file_api + `/api/file-management/files/upload`"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                list-type="picture"
                :headers="headers"
                :limit="1"
                :on-exceed="handleExceed"
                :before-remove="beforeRemove"
                :on-success="handleSuccess"
              >
                <el-button class="uploadButton" size="medium" type="text">+ 点击上传</el-button>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>

      <div class="form-baseinfo basicInfo">
        <p class="title">物料明细</p>
        <el-form ref="inputModel" :model="inputModel" :inline="true" class="form-baseinfo" :rules="rules">
          <div class="info">
            <el-form-item label="物料编码" prop="pNo">
              <el-input v-model="inputModel.pNo" />
            </el-form-item>
            <el-form-item label="物料名称" prop="pTitle">
              <el-input v-model="inputModel.pTitle" />
            </el-form-item>
            <el-form-item label="物料单位" prop="pUnit">
              <el-input v-model="inputModel.pUnit" />
            </el-form-item>
            <el-form-item label="物料价格" prop="pPrice">
              <el-input v-model="inputModel.pPrice" max-length="10" @input="moneyInput" />
              <el-button class="addBtn" size="medium" type="text" @click="insertInfo('inputModel')"
                >+ 添加明细</el-button
              >
            </el-form-item>
          </div>
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :table-data="tableData"
            :table-column="tableColumn"
            :show-page="false"
            align="center"
          >
            <template slot="cz" slot-scope="{ row }">
              <el-button type="text" @click="deleteInfo(row)"> 删除 </el-button>
            </template>
          </LPTablePage>
        </el-form>
        <div class="form-baseinfo">
          <el-button class="button" size="medium" @click="back">关闭</el-button>
          <el-button class="button" size="medium" type="primary" @click="Save('data')">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCategoryInfo } from '@/api/LaborProtection/categoryInfo'
import { updateProduct } from '@/api/LaborProtection/product'
import { getToken } from '@/utils/auth'
import { isFloat } from '@/utils/publicFunction'
import { closeActiveTag } from '@/utils/lpUtils.js'
import LPTablePage from '@/components/LPTablePage/index.vue'

export default {
  name: 'CommodityInsert',
  components: { LPTablePage },
  data() {
    return {
      headers: {
        Authorization: 'bearer ' + getToken()
      },
      inputModel: {
        pNo: '',
        pTitle: '',
        pPrice: undefined,
        pUnit: ''
      },
      data: {
        cName: '',
        bigTypeId: '',
        bigTypeName: '',
        centreTypeId: '',
        centreTypeName: '',
        smallTypeId: '',
        smallTypeName: '',
        imgesUrl: ''
      },
      bigType: [],
      centreType: [],
      smallType: [],
      fileList: [],
      tableData: [],
      // 表格字段
      tableColumn: [
        { label: '物料编码', prop: 'pNo' },
        { label: '物料名称', prop: 'pTitle' },
        // {label: "单位", prop: "unit"},
        { label: '单位', prop: 'pUnit' },
        { label: '价格', prop: 'pPrice' },
        { label: '操作', prop: 'cz', render: true, width: '150' }
      ],
      rules: {
        pNo: [
          { required: true, message: '请输入物料编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        pPrice: [{ required: true, message: '请输入物料价格', trigger: 'blur' }],
        pUnit: [
          { required: true, message: '请输入物料单位', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        pTitle: [
          { required: true, message: '请输入物料名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      rules1: {
        cName: [{ required: true, message: '请输入物料简称', trigger: 'blur' }],
        smallTypeId: [{ required: true, message: '请选择物料小类', trigger: 'change' }],
        centreTypeId: [{ required: true, message: '请选择物料中类', trigger: 'change' }],
        bigTypeId: [{ required: true, message: '请选择物料大类', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getCategoryInfo(1)
  },
  methods: {
    moneyInput(v) {
      this.inputModel.pPrice = v.replace(/^(\d*\.?\d{0,2}).*/, '$1')
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed() {
      this.$message.warning(`限制选择 1 个图片`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(res, file) {
      this.imgesUrl = public_config.file_api + '/api/file-management/files/www/' + file.response
      console.log(this.imgesUrl)
    },
    /**
     *  1：大类 2：中类 3：小类
     * @param {*} type
     */
    getCategoryInfo(type, parentId) {
      const data = {
        CCLass: type,
        SkipCount: 0
      }
      if (parentId) {
        data.parentId = parentId
      }
      getCategoryInfo(data).then((res) => {
        if (!res.error) {
          if (type == 1) {
            this.bigType = res.items
          } else if (type == 2) {
            this.centreType = res.items
          } else {
            this.smallType = res.items
          }
        }
      })
    },
    /**
     * 格式化成树格式
     * @param {*} maps
     */
    setDropDownStructure(maps) {
      return maps.map((item) => {
        return {
          label: item.cName,
          value: item.id
        }
      })
    },
    bigTypeChange(v) {
      this.data.centreTypeId = ''
      this.data.centreTypeName = ''
      this.data.smallTypeId = ''
      this.data.smallTypeName = ''
      this.bigType.forEach((item) => {
        if (item.id == v) {
          this.data.bigTypeName = item.categoryNo
          this.getCategoryInfo(2, item.categoryNo)
        }
      })
    },
    centreTypeChange(v) {
      this.data.smallTypeId = ''
      this.data.smallTypeName = ''
      this.centreType.forEach((item) => {
        if (item.id == v) {
          this.data.centreTypeName = item.categoryNo
          this.getCategoryInfo(3, item.categoryNo)
        }
      })
    },
    smallTypeChange(v) {
      console.log(v)
      this.smallType.forEach((item) => {
        if (item.id == v) {
          this.data.smallTypeName = item.categoryNo
        }
      })
    },

    insertInfo(inputModel) {
      this.$refs[inputModel].validate((valid) => {
        if (valid) {
          const tempList = { ...this.inputModel }
          const p = /[\u4e00-\u9fa5]/
          if (!isFloat(tempList.pPrice)) {
            return this.$message.error('请输入正确的价格')
          }
          console.log(p.test(tempList.pNo))
          if (p.test(tempList.pNo)) {
            return this.$message.error('物料编码不能为中文字符')
          }
          let pNoFalg = false
          this.tableData.forEach((item) => {
            if (item.pNo == this.inputModel.pNo) {
              pNoFalg = true
            }
          })
          if (pNoFalg) {
            return this.$message.error('该物料编码已存在')
          }
          tempList.pPrice = Number(tempList.pPrice)
          console.log(tempList)
          this.tableData.push(tempList)
        } else {
          return false
        }
      })
    },
    deleteInfo(row) {
      const tempLst = []
      this.tableData.forEach((item) => {
        if (item.pNo != row.pNo) {
          tempLst.push(item)
        }
      })
      this.$confirm('是否删除该条数据', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.$message.success('删除成功')
          this.tableData = tempLst
        })
        .catch(() => {})
    },
    back() {
      closeActiveTag(this, '/laborProtection/commodityManage')
    },
    Save(data) {
      this.$refs[data].validate((valid) => {
        if (valid) {
          const submitData = {
            cName: this.data.cName,
            childList: [
              {
                id: this.data.smallTypeId
              }
            ],
            imagesList: [
              {
                imgesUrl: this.imgesUrl
              }
            ],
            productList: []
          }
          console.log(this.tableData.length)
          // return;
          if (this.tableData.length === 0) {
            return this.$message.error('物料明细列表至少需要一条数据')
          }
          submitData.productList = this.tableData
          updateProduct(submitData).then((res) => {
            if (!res.error) {
              this.$message.success('添加成功')
              this.back()
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.commodityDetail {
  margin: 0 45px;

  .form-baseinfo {
    .title {
      font-size: 16px;
      font-weight: 600;
    }

    ::v-deep {
      .el-input-number .el-input__inner {
        text-align: left;
      }
    }

    ::v-deep .el-form-item__error {
      color: #ff4949;
      font-size: 12px;
      line-height: 1;
      padding-top: 4px;
      position: relative;
      top: 100%;
    }
  }
}

::v-deep .el-form-item__label {
  text-align: left;
  font-weight: normal;
  color: #333333;
  line-height: 30px;
}
.basicInfo {
  .info {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: end;
    // margin: 0 45px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ededed;

    .el-form-item {
      display: flex;
      flex-direction: column;
      width: calc(32%);
      height: auto;
      // margin-bottom: 80px;
      &:nth-child(4) {
        position: relative;
      }
    }
    ::v-deep .el-input__inner {
      width: 400px;
      height: 36px;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #d8d8d8;
    }
    .addBtn {
      position: absolute;
      right: 8%;
    }
  }
}
.collect {
  display: block;
  padding-left: 20px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  background-color: #f2f3f5;
}
.title {
  margin-left: 10px;
  padding: 20px 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  &::before {
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    position: absolute;
    left: 45px;
    background: #0076ff;
  }
}

.button {
  width: 100px;
  position: relative;
  left: 45%;
  top: 30px;
  margin: 0 40px;
  transform: translate(-50%);

  &:nth-of-type(1) {
    color: #333333;
    background-color: #fff;
  }
}
</style>
